<template>
  <!-- 主页：输入口令抢红包，发红包按钮，广告！ -->
  <b-container class="page-content" id="home">
    <b-alert show variant="secondary" style="font-size:13px;">
      <b-icon icon="info-circle-fill"></b-icon>
      &nbsp;&nbsp;&nbsp;SERO - 全球第一条可以发行隐私资产的公链
    </b-alert>
    <!-- <img
      src="../assets/home-banner.png"
      class="banner img-fluid"
      referrerPolicy="no-referrer"
    /> -->
    <div class="open-container">
      <div class="top">
        <img alt="Sero logo" class="logo img-fluid" src="../assets/logo.png" />
        <h2 class="title">{{ $t("title") }}</h2>
      </div>

      <b-row>
        <b-col cols="12">
          <div class="get">
            <b-input-group size="lg">
              <b-form-input
                v-model="code"
                placeholder="输入红包口令，抢红包！"
              ></b-form-input>
              <template v-slot:append>
                <b-input-group-text @click="getPackage">抢</b-input-group-text>
              </template>
            </b-input-group>
            <!-- <b-form-text id="input-live-help">领取红包钱包需要留足手续费</b-form-text> -->
          </div>
        </b-col>
      </b-row>
      <div class="send">
        <b-button class="send-btn" variant="warning" @click="goToSendPackage()"
          >我要发红包</b-button
        >
      </div>
    </div>
    <div
      class="redpackage-dialog redpackage-default"
      :class="['redpackage-cover-' + detail.cover]"
      v-show="showPackage"
      @click="hidePackage()"
    >
      <b-overlay
        :show="!detail.code"
        rounded
        opacity="0"
        spinner-small
        spinner-variant="primary"
        class="d-inline-block"
      >
        <div
          class="wrapper"
          @click.stop.prevent="void 0"
          :class="{ animate: detail.code != '' }"
        >
          <div class="top">
            <div class="author">
              <my-img
                v-if="detail.currency"
                :src="'img/token-' + detail.currency.toLowerCase() + '.png'"
                default-img="img/token-sero.png"
              >
              </my-img>
              &nbsp;&nbsp;{{ detail.nickname }}的红包
            </div>
            <p class="desc">{{ detail.note }}</p>
            <p class="open-error" :class="{ animate: openError != '' }">
              {{ openError }}
            </p>
          </div>

          <button
            class="open"
            :class="{ animate: openAnimate }"
            @click="openRedpackage()"
          >
            開
          </button>
          <a href="" class="view" @click.prevent.stop="goDetail()"
            >看看大家的手气<b-icon icon="chevron-right"></b-icon
          ></a>
        </div>
      </b-overlay>
    </div>
  </b-container>
</template>

<script>
// @ is an alias to /src

export default {
  name: "Home",
  components: {},
  methods: {
    hidePackage() {
      this.showPackage = false;
      this.detail.code = "";
    },
    goDetail() {
      this.$router.push({
        name: "Detail",
        query: {
          code: this.detail.code,
          currency: this.detail.currency,
          from: "ViewAll",
        },
      });
    },
    checkNickname() {
      let nickname = localStorage.getItem("nickname");
      if (nickname === null) {
        return true;
      }
      if (!nickname) {
        return false;
      }
      return true;
    },
    getPackage() {
      if (!this.checkNickname()) {
        this.$bvToast.toast("设置昵称后才可以抢红包", {
          title: "提示",
          toaster: "b-toaster-top-center",
          autoHideDelay: 3000,
          appendToast: false,
          variant: "danger",
        });
        return false;
      }
      if (!this.code) {
        return false;
      }
      var codeExp = /^[a-zA-Z0-9]{5,}$/;
      if (codeExp.test(this.code) == false) {
        var match = this.code.match(/红包口令：(?<code>[a-zA-Z0-9]{5,})/);
        if (match) {
          this.code = match.groups.code;
        }
      }
      this.callMethod("packageInfo", [this.code])
        .then(({ detail, canOpen, cover, nickname, note }) => {
          if (!canOpen) {
            this.$bvToast.toast("不能打开此红包", {
              title: "错误",
              toaster: "b-toaster-top-center",
              autoHideDelay: 3000,
              appendToast: false,
              variant: "danger",
            });
            return;
          }
          this.openError = "";
          this.showPackage = true;
          this.detail = {
            code: detail.shareCode,
            nickname: nickname || detail.currency,
            note: note,
            cover: cover,
            currency: detail.currency,
            nums: detail.nums,
            openNums: detail.openNums,
          };
          // console.log("sero:packageInfo ", res);
        })
        .catch((err) => {
          this.$bvToast.toast("获取红包信息错误！" + err, {
            title: "错误",
            toaster: "b-toaster-top-center",
            autoHideDelay: 3000,
            appendToast: false,
            variant: "danger",
          });
        });
    },
    goToSendPackage() {
      this.$router.push({ name: "Send" });
    },
    makeid(length) {
      var result = "";
      var characters =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
      var charactersLength = characters.length;
      for (var i = 0; i < length; i++) {
        result += characters.charAt(
          Math.floor(Math.random() * charactersLength)
        );
      }
      return result;
    },
    openRedpackage() {
      this.openAnimate = true;
      if (parseInt(this.detail.openNums) >= parseInt(this.detail.nums)) {
        setTimeout(() => {
          this.openError = "来晚了，红包抢完了！";
          this.openAnimate = false;
        }, 1000);

        return;
      }

      this.executeMethod("grabPackage", [this.code, this.makeid(12)], 0, "SERO")
        .then((res) => {
          // console.log("sero:grabPackage ", res);
          if (!res) {
            this.openAnimate = false;
            alert("交易发送失败！");
            return;
          }
          //  跳转到交易状态查询页查询成功后，跳转到详情页
          this.$router.push({
            name: "Detail",
            query: {
              code: this.detail.code,
              currency: this.detail.currency,
              txhash: res,
              from: "grabPackage",
            },
          });
        })
        .catch(() => {
          this.openAnimate = false;
          this.openError =
            "不能打开此红包，可能是因为你已经打开此红包或没有权限！";
        });
    },
  },
  created() {
    this.$root.changeNavTitle("");
  },
  data() {
    return {
      openAnimate: false,
      code: "",
      detail: {
        code: "",
        cover: "default",
        currency: "",
        nickname: "",
        note: "",
      },
      openError: "",
      showPackage: false,
    };
  },
};
</script>
<style>
#home {
  height: 100vh;
  display: flex;
  flex-direction: column;
}
#home .open-container {
  display: flex;
  flex-direction: column;
  flex: 1;
  justify-content: center;
}
#home .top {
  text-align: center;
}
#home .banner {
  margin-bottom: 8px;
  border-radius: 3px;
}
#home .logo {
  width: 69px;
}
#home .title {
  margin: 10px 0px;
  font-size: 20px;
}
#home .get {
  margin: 20px 0px 30px;
}
#home .send {
  text-align: center;
}
#home .open-error {
  /* display: none; */
  font-size: 12px;
}
#home .open-error.animate {
  display: block;
  font-size: 22px;
  transition: font-size 0.8s;
}
</style>
